from django.shortcuts import render, redirect
from ..utils.pagination import Pagination
from .. import models
from ..forms import AdminModelForm, AdminResetModelForm, AdminEditModelForm
def admin_list(request):
    # models.Admin.objects.create(username="难受", password=2743)
    # models.Admin.objects.filter(id=2).delete()

    # 构造搜索
    data_dict = {}
    # q = 是展示全部
    search_data = request.GET.get("q")
    if search_data:
        data_dict["username__contains"] = search_data

    # 根据数据条件去数据库获取
    queryset = models.Admin.objects.filter(**data_dict)

    # 分页
    page_object = Pagination(request, queryset, page_size=2)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),
        "search_dict": search_data
    }

    return render(request, "app_02/admin_list.html", context)


def admin_add(request):
    """添加部门"""
    if request.method == "GET":
        form = AdminModelForm()
        return render(request, "app_02/admin_add.html", {"form": form})

    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/app_02/admin/list")

    return render(request, "app_02/admin_add.html", {"form": form})


def admin_edit(request, nid):
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect("/app_02/admin/list/")

    if request.method == "GET":
        form = AdminEditModelForm(instance=row_object)
        return render(request, "app_02/admin_edit.html", {"form": form, "row_object": row_object})

    form = AdminEditModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/app_02/admin/list/")

    return render(request, "app_02/admin_edit.html", {"form": form, "row_object": row_object})


def admin_delete(request, nid):
    models.Admin.objects.filter(id=nid).delete()
    return redirect("/app_02/admin/list/")


def admin_reset(request, nid):
    """重置密码"""
    row_object = models.Admin.objects.filter(id=nid).first()
    if not row_object:
        return redirect("/app_02/admin/list/")

    title = "重置密码 - {}".format(row_object.username)

    if request.method == "GET":
        form = AdminResetModelForm()
        return render(request, "app_02/change.html", {"form": form, "title": title})

    form = AdminResetModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect("/app_02/admin/list/")
    return render(request, "app_02/change.html", {"form": form, "title": title})
